import json

from flask import Blueprint, request, jsonify
from database import db

goods_pd = Blueprint('goods', __name__)


@goods_pd.route('/goods/')
def Goods():
    sql = 'select * from cgood'
    res = db.findall(sql)
    return jsonify({'code': 200, 'list': res})


@goods_pd.route('/cart/', methods=['POST'])
def cart():
    if request.method == "POST":
        data = json.loads(request.data)
        userid = int(data['userid'])
        goodsid = int(data['goodsid'])
        # 加入购物车,查询此人有没有购买过此商品，如果有数量+，没有直接添加
        sql = "select * from cart where userid=%d and goodsid=%d" % (userid, goodsid)
        cart = db.findone(sql)
        if cart:
            count = int(cart['count']) + 1
            sql = "update cart set count=%d where id=%d" % (count, cart['id'])
        else:
            sql = "insert into cart(userid,goodsid,count) values(%d,%d,%d)" % (userid, goodsid, data['count'])
        try:
            db.insert(sql)
            return jsonify({"code": 200})
        except:
            return jsonify({"code": 20010})
